package com.hbzhit.modules.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hbzhit.common.annotation.SysLog;
import com.hbzhit.common.exception.RRException;
import com.hbzhit.common.utils.Constant;
import com.hbzhit.common.utils.R;
import com.hbzhit.modules.sys.entity.SysMenuEntity;
import com.hbzhit.modules.sys.entity.SysUserEntity;
import com.hbzhit.modules.sys.service.ShiroService;
import com.hbzhit.modules.sys.service.SysMenuService;
import com.hbzhit.modules.sys.vo.SysMenuQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 系统菜单
 *
 * @author Mark sunlightcs@gmail.com
 */
@Api(tags = {"菜单管理"})
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private ShiroService shiroService;

	/**
	 * 导航菜单
	 */
	@ApiOperation(value = "系统菜单导航", notes = "根据用户权限获取菜单")
	@GetMapping("/nav")
	public R<Object> nav(SysMenuQueryVO params) {
		List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(params);
		Set<String> permissions = shiroService.getUserPermissions(params);
		return R.ok().put("menuList", menuList).put("permissions", permissions);
	}

	/**
	 * 所有菜单列表
	 */
	@ApiOperation("菜单列表")
	@GetMapping("/list")
	public R<List<SysMenuEntity>> list(SysMenuQueryVO params){
		LambdaQueryWrapper<SysMenuEntity> query = new LambdaQueryWrapper<>();
		query.orderByAsc(SysMenuEntity::getOrderNum);
		SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		List<SysMenuEntity> menuList = sysMenuService.list(new LambdaQueryWrapper<SysMenuEntity>()
				.eq(SysMenuEntity::getProp, params.getProp())
				.inSql(user.getId() != Constant.SUPER_ADMIN, SysMenuEntity::getId, StrUtil.format("select rm.menu_id from sys_role_menu rm join sys_user_role ur on rm.role_id = ur.role_id where ur.user_id={}", user.getId()))
				.orderByAsc(SysMenuEntity::getOrderNum)
		);

		return R.ok(menuList);
	}

	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@ApiOperation(value = "选择菜单", notes = "不包含资源权限的菜单列表")
	@GetMapping("/select")
	public R<List<SysMenuEntity>> select(SysMenuQueryVO params){
		//查询列表数据
		List<SysMenuEntity> menuList = sysMenuService.list(new LambdaQueryWrapper<SysMenuEntity>()
				.eq(SysMenuEntity::getProp, params.getProp())
				.ne(SysMenuEntity::getType, 2)
				.orderByAsc(SysMenuEntity::getOrderNum)
		);

		return R.ok(menuList);
	}

	/**
	 * 菜单信息
	 */
    @ApiOperation("菜单详情")
	@GetMapping("/info/{menuId}")
	public R<SysMenuEntity> info(@PathVariable("menuId") Long menuId){
		SysMenuEntity menu = sysMenuService.getById(menuId);
		return R.ok(menu);
	}

	/**
	 * 保存
	 */
	@ApiOperation("菜单保存")
	@SysLog("保存菜单")
	@PostMapping("/save")
	@RequiresPermissions("sys:menu:save")
	public R<Object> save(@RequestBody SysMenuEntity menu){
		//数据校验
		verifyForm(menu);
		sysMenuService.save(menu);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@ApiOperation("菜单修改")
	@SysLog("修改菜单")
	@PostMapping("/update")
	@RequiresPermissions("sys:menu:update")
	public R<Object> update(@RequestBody SysMenuEntity menu){
		//数据校验
		verifyForm(menu);
		sysMenuService.updateById(menu);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@ApiOperation("菜单删除")
	@SysLog("删除菜单")
	@PostMapping("/delete/{menuId}")
	@RequiresPermissions("sys:menu:delete")
	public R<Object> delete(@PathVariable("menuId") long menuId){
		if(menuId <= 31){
			return R.error("系统菜单，不能删除");
		}

		//判断是否有子菜单或按钮
		List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
		if(CollUtil.isNotEmpty(menuList)){
			return R.error("请先删除子菜单或按钮");
		}

		sysMenuService.delete(menuId);

		return R.ok();
	}

	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(SysMenuEntity menu){
		if(StringUtils.isBlank(menu.getName())){
			throw new RRException("菜单名称不能为空");
		}

		if(menu.getParentId() == null){
			menu.setParentId(0L);
		}

		//菜单
		if(menu.getType() == Constant.MenuType.MENU.getValue()){
			if(StringUtils.isBlank(menu.getUrl())){
				throw new RRException("菜单URL不能为空");
			}
		}

		//上级菜单类型
		int parentType = Constant.MenuType.CATALOG.getValue();
		if(menu.getParentId() != 0){
			SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
			parentType = parentMenu.getType();
		}

		//目录、菜单
		if(menu.getType() == Constant.MenuType.CATALOG.getValue() ||
				menu.getType() == Constant.MenuType.MENU.getValue()){
			if(parentType != Constant.MenuType.CATALOG.getValue()){
				throw new RRException("上级菜单只能为目录类型");
			}
			return ;
		}

		//按钮
		if(menu.getType() == Constant.MenuType.BUTTON.getValue()){
			if(parentType != Constant.MenuType.MENU.getValue()){
				throw new RRException("上级菜单只能为菜单类型");
			}
		}
	}

	/**
	 * 查询所有下级
	 */
	@ApiOperation("查询所有下级")
	@GetMapping("/queryAllChildren")
	public R<List<SysMenuEntity>> queryAllChildren(@RequestParam @ApiParam(value = "父级id", required = true) Long parentId){
		return R.ok(sysMenuService.queryAllChildren(parentId));
	}
}
